/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.example.servletdemo.config;

import com.luter.heimdall.core.authorization.provider.DocumentAuthorityDataProvider;
import com.luter.heimdall.core.authorization.store.MemoryCachedAuthorizationStore;
import com.luter.heimdall.core.context.WebContextHolder;
import com.luter.heimdall.core.limiter.MemoryCachedPasswordRetryLimiter;
import com.luter.heimdall.core.limiter.PasswordRetryLimiter;
import com.luter.heimdall.core.manager.AuthenticationManager;
import com.luter.heimdall.core.manager.AuthorizationManager;
import com.luter.heimdall.core.manager.HeimdallAuthenticationManager;
import com.luter.heimdall.core.manager.HeimdallAuthorizationManager;
import com.luter.heimdall.core.token.id.UUIDIdGenerator;
import com.luter.heimdall.core.token.store.MemoryCachedTokenStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * heimdall 配置
 *
 * @author luter
 */
@Configuration
public class HeimdallConfig {

    /**
     * 认证管理器
     *
     * @param webContextHolder the web context holder
     * @return the authentication manager
     */
    @Bean
    public AuthenticationManager authenticationManager(WebContextHolder webContextHolder) {
        return new HeimdallAuthenticationManager(webContextHolder).idGenerator(new UUIDIdGenerator())
                .tokenStore(new MemoryCachedTokenStore());

    }

    /**
     * 授权管理器
     *
     * @param authenticationManager the authentication manager
     * @return the authorization manager
     */
    @Bean
    public AuthorizationManager authorizationManager(AuthenticationManager authenticationManager) {
        //系统权限数据，采用 yaml 文档数据源
        final MemoryCachedAuthorizationStore memoryCachedAuthorizationStore =
                new MemoryCachedAuthorizationStore().dataProvider(new DocumentAuthorityDataProvider());
        return new HeimdallAuthorizationManager(memoryCachedAuthorizationStore, authenticationManager);
    }

    /**
     * 密码重试次数限制
     *
     * @return the password retry limiter
     */
    @Bean
    public PasswordRetryLimiter passwordRetryLimiter() {
        return new MemoryCachedPasswordRetryLimiter();
    }
}
